package org.ztest.zip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPTest
{
    public byte[] compress(byte[] plainData) throws IOException
    {
        try (ByteArrayOutputStream bao = new ByteArrayOutputStream())
        {
            GZIPOutputStream gzip = new GZIPOutputStream(bao);
            gzip.write(plainData);
            gzip.close();
            return bao.toByteArray();
        }
    }
    
    public byte[] deCompress(byte[] cipherData) throws IOException
    {
        try (ByteArrayInputStream bai = new ByteArrayInputStream(cipherData);
             ByteArrayOutputStream bao = new ByteArrayOutputStream())
        {
            GZIPInputStream gzip = new GZIPInputStream(bai);
            byte[] buf = new byte[128];
            int n = 0;
            while ((n = gzip.read(buf)) > 0)
            {
                bao.write(buf, 0, n);
            }
            return bao.toByteArray();
        }
    }
}
